package main

import (
	"fmt"
	"os"
	"encoding/json"
)

type ContactInfo struct {
	Phone string `json:"phone"`
	Address string `json:"address"`
}

type Person struct {
	FirstName string `json:"firstName"`
	LastName string `json:"lastName"`
	Contacts []*ContactInfo `json:"contacts"`
}

func main() {
	home:=ContactInfo{"111", "home address"}
	work:=ContactInfo{"222", "work address"}
	info:=[]*ContactInfo{&home, &work}
	person:=Person{"Da", "Maomao", info}

	jPerson,_:=json.MarshalIndent(person, "","  ");
	fmt.Println(string(jPerson))

	person2:=Person{}
	json.Unmarshal(jPerson,&person2)
	fmt.Println("person2:", person2)

	// ---------------
	file,_:=os.OpenFile("test.json", os.O_WRONLY | os.O_CREATE, 0666)
	enc:=json.NewEncoder(file)
	enc.Encode(person)
	file.Close()

	file2,_:=os.OpenFile("test.json", os.O_RDONLY, 0)
	dec:=json.NewDecoder(file2)
	person3:=Person{}
	dec.Decode(&person3)
	fmt.Println(person3)
}
